package org.springframework.validation;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.validation.rules.ValidationRule;

public class ValidationEntity {
	
	Log log = LogFactory.getLog(ValidationEntity.class);

	private List<ValidationRule> modelValidationRules;
	private Map<String, List<ValidationRule>> contextValidationRules;
	private Class validationClass;
	
	public ValidationEntity() {
		this.modelValidationRules = new ArrayList<ValidationRule>();
		this.contextValidationRules = new HashMap<String, List<ValidationRule>>();
	}
	
	public void addModelValidationRule(ValidationRule rule) {
		this.modelValidationRules.add(rule);
	}
	
	public void addContextValidationRule(String state, ValidationRule rule) {
		this.contextValidationRules.get(state).add(rule);
	}
	
	public List<ValidationRule> getContextValidationRules(String form) {
		List<ValidationRule> formRules = new ArrayList<ValidationRule>();
		for (String formName : contextValidationRules.keySet()) {
			String formPattern = formName.replaceAll("\\{[^\\}]*}", "[^/]+");
			if (form.matches(formPattern)) {
				log.debug("Loading rules for form: " + form + ", matched validation rules @ " + formName);
				formRules.addAll(contextValidationRules.get(formName));
			}
		}
		return formRules;
	}
	
	public List<ValidationRule> getModelValidationRules() {
		return modelValidationRules;
	}

	/**
	 * @param modelValidationRules the modelValidationRules to set
	 */
	public void setModelValidationRules(List<ValidationRule> modelValidationRules) {
		this.modelValidationRules = modelValidationRules;
	}

	/**
	 * @param contextValidationRules the contextValidationRules to set
	 */
	public void setContextValidationRules(Map<String, List<ValidationRule>> contextValidationRules) {
		this.contextValidationRules = contextValidationRules;
	}
	
	/**
	 * @param contextValidationRules the contextValidationRules to set
	 */
	public void addContextValidationRules(String state, List<ValidationRule> contextValidationRuleList) {
		this.contextValidationRules.put(state, contextValidationRuleList);
	}

	public Class getValidationClass() {
		return validationClass;
	}

	public void setValidationClass(Class validationClass) {
		this.validationClass = validationClass;
	}
	

}
